package ext.acae2.cad.client;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.TimeZone;

import org.apache.log4j.Logger;

import wt.change2.ChangeHelper2;
import wt.change2.Changeable2;
import wt.change2.WTChangeOrder2;
import wt.epm.EPMDocument;
import wt.epm.EPMDocumentType;
import wt.fc.Persistable;
import wt.fc.QueryResult;
import wt.fc.collections.WTCollection;
import wt.fc.collections.WTHashSet;
import wt.fc.collections.WTKeyedHashMap;
import wt.fc.collections.WTSet;
import wt.lifecycle.State;
import wt.log4j.LogR;
import wt.maturity.MaturityHelper;
import wt.maturity.PromotionNotice;
import wt.org.WTUser;
import wt.util.WTException;
import wt.vc.VersionControlHelper;
import wt.workflow.definer.UserEventVector;
import wt.workflow.engine.WfEngineHelper;
import wt.workflow.engine.WfProcess;
import wt.workflow.engine.WfState;
import wt.workflow.engine.WfVotingEventAudit;

import com.ptc.netmarkets.workflow.NmWorkflowHelper;

import ext.acae2.ACAEConstants;
import ext.acae2.cad.CADSignHelper;
import ext.acae2.utilities.util.CSCUtil;

/**
 * @desription CAD sign Service
 * @author cnie
 * @date 2013-7-23 下午3:17:09
 */
public class CADSignService {
	
	
	private static final List<String> signActivityNames = new ArrayList<String>();
	
	private static final Logger LOGGER = LogR.getLogger(CADSignService.class.getName());
	
	static{
		signActivityNames.add("校对");
		signActivityNames.add("批准");
		signActivityNames.add("审核");
		signActivityNames.add("会签");
		signActivityNames.add("标审");
		signActivityNames.add("标审");
		signActivityNames.add("编制");
		signActivityNames.add("修改");
	}
	
	
	public static Map<String, String> getProcessRouteHistory(Persistable p)
			throws Exception {
		Map<String, String> signInfo = new HashMap<String, String>();
		WTSet set = new WTHashSet();
		if(p instanceof EPMDocument){
			QueryResult iterationQr = VersionControlHelper.service.iterationsOf((EPMDocument)p); //获取当前大版本的所有小版本
			while(iterationQr.hasMoreElements()){
				set.add(iterationQr.nextElement());
			}
		}
//		set.add(p);
		WTKeyedHashMap keyMap = MaturityHelper.getService()
				.getPromotionNotices(set,
						State.toState("APPROVED"));
		PromotionNotice pn = null;
		WTChangeOrder2 ecn = null;
		for(java.util.Iterator iterationIt = set.iterator();iterationIt.hasNext();){
			Object iterationObj = iterationIt.next();
			WTCollection collection = (WTCollection) keyMap.get(iterationObj);
			if (collection == null || collection.size() == 0) 
				continue;
			else{
				java.util.Iterator it = collection.persistableIterator();
				if (it.hasNext()) {
					pn = (PromotionNotice) it.next();
				}
				break;
			}
		}
		if(pn==null){
			QueryResult qr = ChangeHelper2.service
					.getLatestUniqueImplementedChangeOrders((Changeable2) p);
			while (qr != null && qr.size() != 0 && qr.hasMoreElements()) {
				WTChangeOrder2 wtChangeOrder = (WTChangeOrder2) qr
						.nextElement();
				if (State.toState(ACAEConstants.ACAE2_RELEASED_STATE_NAME)
						.equals(wtChangeOrder.getState().getState())) {
					ecn = wtChangeOrder;
					break;
				}
			}
		}
		QueryResult processes = new QueryResult();
		if (pn != null) {
			processes = WfEngineHelper.service.getAssociatedProcesses(pn,
					WfState.CLOSED_COMPLETED_EXECUTED,
					pn.getContainerReference());
			if(processes==null||!processes.hasMoreElements()){
				processes = WfEngineHelper.service.getAssociatedProcesses(pn,
						WfState.OPEN_RUNNING,
						pn.getContainerReference());
			}
		} else {
			if (ecn != null) {
				processes = WfEngineHelper.service.getAssociatedProcesses(ecn,
						WfState.CLOSED_COMPLETED_EXECUTED,
						ecn.getContainerReference());
			}
		}
		
		int index = 1; // 会签的标识
		if (processes.hasMoreElements()) {
			WfProcess process = (WfProcess) processes.nextElement();
			QueryResult qsVoteEvent = NmWorkflowHelper.service
					.getVotingEventsForProcess(process);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			sdf.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
			while (qsVoteEvent.hasMoreElements()) {
				WfVotingEventAudit voteEvent = (WfVotingEventAudit) qsVoteEvent
						.nextElement();
				String activityName = voteEvent.getActivityName();
				if (signActivityNames.contains(activityName)) {
					String endTime = sdf.format(voteEvent.getTimestamp());
					WTUser completeByUser = (WTUser) voteEvent.getUserRef()
							.getPrincipal();
					String fullName = completeByUser.getFullName();
					if ("会签".equals(activityName)) {
						if (index <= 5) {
							signInfo.put(activityName + index, fullName);
							signInfo.put(activityName + index + "日期", endTime);
							index++;
						}
					} else if ("批准".equals(activityName)) {
						signInfo.put("批准者", fullName);
						signInfo.put("批准日期", endTime);
					} else if ("编制".equals(activityName)
							|| "修改".equals(activityName)) {
						signInfo.put("设计", fullName);
						signInfo.put("设计日期", endTime);
						break;
					} else {
						signInfo.put(activityName, fullName);
						signInfo.put(activityName + "日期", endTime);
					}
				}

			}
		}
		return signInfo;
	}
	
	/**
	 * 
	 * @description 历史数据的方法
	 * @author cnie
	 * @date 2013-8-9 下午3:25:53
	 * @version 1.0
	 * @param oids
	 * @return
	 * @throws Exception
	 */
	public static String sign(String oids) throws Exception{
		Map<EPMDocument, Map<String,String>> cadSignMap = new HashMap<EPMDocument, Map<String,String>>();
		List<String> errorList = new ArrayList<String>();
		StringTokenizer st = new StringTokenizer(oids, "#");
		while(st.hasMoreElements()){
			String oid = st.nextToken();
			LOGGER.debug("========oid>"+oid);
			
			EPMDocument epmdocument = (EPMDocument) CSCUtil.getObjectByOid(oid);
			if(!EPMDocumentType.toEPMDocumentType("CADDRAWING").equals(epmdocument.getDocType())){
				errorList.add("编号："+epmdocument.getNumber()+" 不是二维图纸，跳过签名");
				continue;
			}
				
			Map<String,String> signInfo = getProcessRouteHistory(epmdocument);
			LOGGER.debug("------------------------------------------------------------------");
			for(java.util.Iterator<String> signInfoIt = signInfo.keySet().iterator();signInfoIt.hasNext();){
				String key = signInfoIt.next();
				String value = signInfo.get(key);
				LOGGER.debug("signInfo>>>>>>>>>>>>>>>"+key+":::::::"+value);
			}
			LOGGER.debug("------------------------------------------------------------------");
			if(signInfo==null||signInfo.size()==0){
				errorList.add("编号："+epmdocument.getNumber()+" 没有签署信息");
				continue;
			}
			cadSignMap.put(epmdocument, signInfo);
		}
		CADSignHelper.signCADSOverride(cadSignMap,errorList,false);
		if(errorList==null||errorList.size()==0){
			return "success";
		}else{
			StringBuffer sb = new StringBuffer();
			for(String errorStr:errorList){
				sb.append(errorStr);
				sb.append("<br/>");
			}
			return sb.toString();
		}
	}

}
